﻿using Android.Content;
using Android.Graphics;
using Android.Hardware.Display;
using Android.Media.Projection;
using Android.Media;
using Android.Views;
using Java.Interop;
using static Android.Text.BoringLayout;

namespace ScreenShotDemo
{
    /// <summary>
    /// 悬浮窗实现
    /// </summary>
    public class FloatingWindowHepler
    {
        private static IWindowManager? _windowManager;
        private static View? _floatingView;
        private static WindowManagerLayoutParams? _layoutParams;
        public static void InitFloatingWindowHepler(Service service)
        {
            var layoutInflater = LayoutInflater.From(service);
            if (layoutInflater == null)
            {
                throw new InvalidOperationException("LayoutInflater could not be retrieved.");
            }
            _floatingView = layoutInflater.Inflate(Resource.Layout.floating_window, null)
                ?? throw new InvalidOperationException("Inflation of the floating window layout failed.");
            _windowManager = service.GetSystemService(Context.WindowService)?.JavaCast<IWindowManager>();
            if (_windowManager == null)
            {
                throw new InvalidOperationException("WindowManager could not be retrieved.");
            }
            _layoutParams = new WindowManagerLayoutParams(
                80,
                80,
                WindowManagerTypes.ApplicationOverlay,
                WindowManagerFlags.NotFocusable,
                Format.Translucent);
            _layoutParams.Gravity = GravityFlags.Bottom | GravityFlags.Left;
            _layoutParams.X = 0;
            _layoutParams.Y = 0;
            //_layoutParams.Flags = WindowManagerFlags.NotTouchable;此属性悬浮窗不可点击
            _windowManager.AddView(_floatingView, _layoutParams);
            //悬浮窗加载后，给按钮绑定点击事件
            var clickBtn = _floatingView?.FindViewById<Button>(Resource.Id.click_this);
            CommUtils.WriteLog($"加载按钮事件!{clickBtn.Text}");
            if (clickBtn != null)
            {
                clickBtn.Click += (s, e) =>
                {
                    //MyMediaProjectionService._captureScreenHelper.setupSingleFrameCapture();
                    //TaskHepler taskHepler = TaskHepler.GetTaskHepler();
                    //taskHepler.StartTask(async () =>
                    //{
                        //CommUtils.WriteLog($"点击了悬浮窗按钮!{clickBtn.Text}");
                        MyMediaProjectionService._captureScreenHelper.setupSingleFrameCapture();
                    //});
                };
            }
        }

        public static void Dispose()
        {
            _floatingView?.Dispose();
            _layoutParams?.Dispose();
            _windowManager?.Dispose();
        }
    }
}
